package com.fingard.dsp.bank.directbank.csrsybt11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class CSRSYBT11BatPayRec extends CSRSYBT11Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req1988.reqHeader);
        retAts.reqSeqID = p_req1988.reqBatchNO;

        FtpPortClient ftpPortClient = null;

        try {
            // 代收付文件内容
            StringBuilder sbFileContent = new StringBuilder();

            // 汇总信息：总笔数|总金额\r\n
            String tmpReqHeader = MessageFormat.format("{0}|{1}\r\n", p_req1988.totalNum, p_req1988.totalAmt);
            sbFileContent.append(tmpReqHeader);

            // 文件明细
            StringBuilder seqNoMappingContent = new StringBuilder();
            while (p_req1988.readRecord()) {
                if (seqNoMappingContent.length() > 0) {
                    seqNoMappingContent.append("\r\n");
                }
                seqNoMappingContent.append(p_req1988.readedDetail.askNumber);

                String postScript = p_req1988.readedDetail.askNumber;
                String policyNo = p_req1988.readedDetail.memo;
                String payAmt = p_req1988.readedDetail.payAmount;
                String tbReason = p_req1988.readedDetail.purpose;
                String memo = p_req1988.readedDetail.askNumber;

                // 明细信息:订单号|保单号|划拨金额|划拨原因|备注\r\n
                String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}|{3}|{4}\r\n", postScript, policyNo, payAmt, tbReason, memo);
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批次退保待处理文件内容:\r\n" + sbFileContent.toString());

            // 上传文件保存本地: FUNCSTRANS.YYYYMMDD
            String tmpUploadFileName = "FUNCSTRANS." + Format.Date8Format.format(p_req1988.getPayDateTime());
            String tmpLocalMarkPath = getTempFileDirectory(p_req1988.reqHeader.srcBankCode) + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批次退保待处理文件保存本机路径: " + tmpLocalMarkPath);

            if (FileHelper.existFile(tmpLocalMarkPath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                retAts.reqSeqID = p_req1988.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }

            FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());

            // 退保流水映射存入本地
            WriteBankLogLn2("本地退保流水映射文件内容:\r\n" + seqNoMappingContent.toString());
            String refundSeqNoPath = getDataFileDirectory(p_req1988.getPayDateTime()) + File.separator + p_req1988.reqBatchNO + ".txt";
            WriteBankLogLn2("本地退保流水映射文件路径:" + refundSeqNoPath);
            FileHelper.writeFile(refundSeqNoPath, seqNoMappingContent.toString(), getCharset());

            // 上送银保通服务器
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            WriteBankLogLn("上传地址:" + ftpSet.serverIP + ":" + ftpSet.port);
            ftpSet.upDir = getBankConfig().getMapValueByKey("ftpSetMapping",p_req1988.reqHeader.srcBankCode + "-upload");
            WriteBankLogLn2("上传ftp服务器目录:" + ftpSet.upDir);
            ftpPortClient = new FtpPortClient(ftpSet);
            FtpReceiver ftpReceiver = ftpPortClient.uploadFile(tmpLocalMarkPath, tmpUploadFileName);

            retAts.respCode = "0";
            retAts.reqSeqID = p_req1988.reqBatchNO;
            if (!ftpReceiver.isCompleted) {
                retAts.respCode = "-1";
                retAts.respInfo = ftpReceiver.connMsg;
            } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                retAts.respInfo = "上传失败";
                retAts.transState = "BatchFailed";
                retAts.payInfoCode = "E9999";
            } else {
                retAts.respInfo = "上传成功";
                retAts.transState = "Uploaded";
                retAts.payInfoCode = "I4001";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPortClient != null) {
                ftpPortClient.disconnect();
            }
        }

        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req1998.reqHeader);
        retAts.reqSeqID = p_req1998.reqBatchNO;

        FtpPortClient ftpPortClient = null;

        try {
            String refundSeqNoPath = getDataFileDirectory(p_req1998.getBgnDateTime()) + File.separator + p_req1998.reqBatchNO + ".txt";
            WriteBankLogLn2("本地退保流水映射文件路径:" + refundSeqNoPath);
            if (!new File(refundSeqNoPath).exists()) {
                retAts.respCode = "-1";
                retAts.respInfo = "本地退保流水文件不存在!";
                retAts.writeAfterDetail();
                return retAts;
            }

            String seqNoContent = FileHelper.readFileText(refundSeqNoPath, getCharset());
            WriteBankLogLn2("本地退保流水映射文件内容:\r\n" + seqNoContent);
            String[] seqNoArray = seqNoContent.split("\r\n");

            // 下载文件名命名规则:FUNCSTRANS.RESULE.YYYYMMDD
            String tmpDownFileName = "FUNCSTRANS.RESULT." + Format.Date8Format.format(p_req1998.getBgnDateTime());

            FtpSet ftpSet = bankFront.getFtpSet("bat");
            WriteBankLogLn("下载地址:" + ftpSet.serverIP + ":" + ftpSet.port);
            ftpSet.downDir = getBankConfig().getMapValueByKey("ftpSetMapping",p_req1998.reqHeader.srcBankCode + "-download");
            WriteBankLogLn2("下载ftp服务器目录:" + ftpSet.downDir);

            ftpPortClient = new FtpPortClient(ftpSet);
            FtpReceiver ftpReceiver = ftpPortClient.listFiles(ftpSet.downDir);
            if (!ftpReceiver.isCompleted) {
                retAts.respCode = "-1";
                if (ConnState.FILE_NOT_EXISTS.equals(ftpReceiver.connState)) {
                    retAts.respInfo = "FTP服务器批次结果文件尚未生成!";
                } else {
                    retAts.respInfo = "遍历目录:" + ftpSet.downDir + "失败!";
                }
                retAts.writeAfterDetail();
                return retAts;
            }

            List<String> fileNameList = Arrays.asList(ftpReceiver.connMsg.split(","));
            Iterator<String> iterator = fileNameList.iterator();
            while (iterator.hasNext()) {
                String ftpFileName = ((String) iterator.next()).toString();
                if (ftpFileName.contains(tmpDownFileName)) {
                    tmpDownFileName = ftpFileName;
                }
            }
            String tmpLocalMarkPath = createTempFileDirectory() + File.separator + tmpDownFileName;
            WriteBankLogLn2("批量代付结果文件保存本地路径: " + tmpLocalMarkPath);

            ftpReceiver = ftpPortClient.downloadFile(tmpDownFileName, tmpLocalMarkPath);

            if (ftpReceiver.isCompleted) {
                String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);

                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    retAts.respCode = "0";
                    retAts.reqSeqID = p_req1998.reqBatchNO;

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    tmpReader.readLine();

                    while(true) {
                        String eachline = tmpReader.readLine();
                        if(StringHelper.isNullOrEmpty(eachline)){
                            break;
                        }
                        if (eachline.indexOf("|") > 0) {
                            // 明细记录:序列号|客户账号|交易金额(单位:分)|借贷标志|摘要|错误代码|失败原因\n
                            String[] bodyValues = eachline.split("\\|");

                            for (String tmpSeqNo : seqNoArray) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

                                if (tmpSeqNo.equals(bodyValues[5])) {
                                    tmpRetDetail.postScript = bodyValues[5];
                                    tmpRetDetail.payAmount = bodyValues[2];
                                    tmpRetDetail.result = "0+" + bodyValues[3];
                                    tmpRetDetail.payInfoCode = bodyValues[4];
                                    tmpRetDetail.memo = bodyValues[4];

                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "银行返回明细数据格式非法!";
                        }
                    }

                    if (!retAts.getRetAtsString().contains("<DetailRecord")) {
                        retAts.respInfo = "没有满足条件的记录!";
                        retAts.transState = PaymentState.FAIL_Batch;
                        retAts.payInfoCode = "E1302";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地批次结果文件内容为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "退保结果文件下载失败:" + ftpReceiver.connMsg;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        } finally {
            if (ftpPortClient != null) {
                ftpPortClient.disconnect();
            }
        }

        retAts.writeAfterDetail();
        return retAts;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return null;
    }
}